from django.shortcuts import render,get_object_or_404,redirect

# Create your views here.
from django.contrib.auth.models import User
from django.http import HttpResponse,Http404
from .models import Board,Topic,Post
from .forms import NewTopicForm

from django.utils.datastructures import MultiValueDictKeyError


def home(request):
    # return HttpResponse("Study second django project")
    boards = Board.objects.all()
    return render(request,'home.html',{'boards': boards})
    
# django有快捷方式去得到一个对象,返回一个不存在的对象404
def board_topics(request,pk):
    board = get_object_or_404(Board,pk=pk)
    return render(request,'topics.html',{'board': board})


def new_topic(request,pk):
    board = get_object_or_404(Board,pk=pk)
    user = User.objects.first()


    # 表单处理的部分
    if request.method == 'POST':
        # 实例化一个将POST数据传递给form的form实例
        form = NewTopicForm(request.POST)

        # 表单有效,使用form.save()将数据存入数据库.
        if form.is_valid():
            topic = form.save(commit=False)
            topic.board = board 
            topic.starter = user 
            # save()方法返回一个存入数据库的Model实例
            topic.save()

            post = Post.objects.create(
                message = form.cleaned_data.get('message'),
                topic = topic,
                created_by = user
            )
            # 重定向到创建的topic页面
            return redirect('board_topics',pk=board.pk) 

    else:
        # 请求时GET, 初始化一个新的空表单.
        form = NewTopicForm()
    # 如果数据无效, 需要更新new_topic.html 以显示错误.
    return render(request,'new_topic.html',{'board': board,'form':form})
